const fs = require('fs');

const logger = require('koa-logger');
const bodyParser = require('koa-bodyparser');
const Router = require('koa-router');
const serve = require('koa-static');
const jwt = require('koa-jwt');
const cors = require('kcors');

const config = require('./environment');

module.exports = app => {
  if (config.app.env !== 'test') {
    app.use(logger());
  }

  app.use(serve(config.staticServe.root));
  app.use(cors());
  app.use(bodyParser());
  app.use(jwt({ secret: config.app.secret }).unless({ path: [/^\/api\/auth/] }));

  // mount all the routers defined in resources
  const router = new Router({ prefix: '/api' });
  fs.readdirSync('./server/resources').forEach(dirName => {
    require(`../resources/${dirName}`).init(router);  // eslint-disable-line global-require
  });
  app
    .use(router.routes())
    .use(router.allowedMethods());
};
